package com.itheima.day16_网络编程.Test02;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket s = new ServerSocket(10000);
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                3,
                10,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
        while (true) {
            Socket a = s.accept();
            Runnable r = () -> {
                try {
                    InputStream is = a.getInputStream();
                    FileOutputStream fos = new FileOutputStream("homework\\" + UUID.randomUUID().toString() + ".jpg");
                    int i;
                    byte[] b = new byte[1024];
                    while ((i = is.read(b)) != -1) {
                        fos.write(b, 0, i);
                    }
                    OutputStream os = a.getOutputStream();
                    os.write("上传成功".getBytes());
                    fos.close();
                    a.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            };
            pool.submit(r);
        }
    }
}
